// 链接数据库，创建用户合集，向集合中插入文档
// 当用户访问/list，将所有用户信息查询出来
// 实现路由功能
// 呈现用户列表页面
// 从数据库中查询用户信息，将用户信息展示在列表中
// 将用户信息和表格HTML进行拼接并将拼接结果响应回客户端
// 当访问/add，呈现表单页面，并实现添加用户功能
// 当访问/modify，呈现修改页面，并实现修改用户信息功能
// 修改用户信息分为两大步骤
    // 1.增加页面路由 呈现页面
          // 1.点击修改按钮，将用户ID传递到当前的页面
          // 2.从数据库中查询当前用户信息，然后展示到页面中
    // 2.实现用户修改功能
          // 1.指定表单的提交地址以及请求方式
          // 2.接受客户端传递过来的修改信息，找到用户 将用户信息更改为最新的


const http = require('http');
const url = require('url');
const querystring = require('querystring');

//引入
require('./model/index');
const User = require('./model/user')


const app = http.createServer();

app.on('request', async (req, res) => {
  const method = req.method;

  const {
    pathname ,query
  } = url.parse(req.url, true);

  if (method == 'GET') {
    // 呈现用户列表页面
    if (pathname == '/list') {
      let users = await User.find();
      // console.log(users);
      // html 字符串
      let list = `
      <!DOCTYPE html>
      <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
      </head>
      <body>
        <div class="container">
          <h6>
            <a href="/add" >添加用户</a>
          </h6>
          <table border="1">
            <tr>
              <td>用户名</td>
              <td>年龄</td>
              <td>爱好</td>
              <td>邮箱</td>
              <td>操作</td>
            </tr>
      `
      users.forEach(item => {
        list += `
        <tr>
          <td>${item.name}</td>
          <td>${item.age}</td>
          <td>
        `
        item.hobbies.forEach(item => {
          list += `<span>${item}</span>`
        })
        list += `
          </td>
          <td>${item.email}</td>
          <td>
            <a href="/remove?id=${item._id}">删除</a>
            <a href="/modify?id=${item._id}">修改</a>
          </td>
        </tr>
        `
      })


      list += `
      </table>
      </div>
    </body>
    </html>
      `
      res.end(list);
    } else if (pathname == '/add') {
      let add = `
      <!DOCTYPE html>
      <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
      </head>
      <body>
        <div class="container">
          <h1>添加用户</h1>
          <form action="/add" method="post">
            <div class="seaction">
              <span>用户名</span>
              <input name="name" type="text" placeholder="请输入用户名">
            </div>
            <div class="seaction">
              <span>密码</span>
              <input name="password" type="text" placeholder="请输入密码">
            </div>
            <div class="seaction">
              <span>年龄</span>
              <input name="age" type="text" placeholder="请输入年龄">
            </div>
            <div class="seaction">
              <span>邮箱</span>
              <input name="email" type="text" placeholder="请输入邮箱">
            </div>
            <div class="seaction">
              <span>请选择爱好</span>
              <div>
                <label>
                  <input type="checkbox" value="足球" name="hobbies">足球
                </label>
                <label>
                  <input type="checkbox" value="篮球" name="hobbies">篮球
                </label>
                <label>
                  <input type="checkbox" value="敲代码" name="hobbies">敲代码
                </label>
                <label>
                  <input type="checkbox" value="打游戏" name="hobbies">打游戏
                </label>
            </div>
            <button type="submit">添加用户</button>
          </form>
        </div>
      </body>
      </html>
      `
      res.end(add)
    } else if (pathname == '/modify') {
      let user = await User.findOne({_id:query.id}) // 注意查询单条用findOne
      let hobbies = ['足球','篮球','敲代码','打游戏']
      console.log(user);
      // 修改页面
      let modify = `
      <!DOCTYPE html>
      <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
      </head>
      <body>
        <div class="container">
          <h1>修改用户</h1>
          <form action="/modify?id=${user._id}" method="post">
          <div class="seaction">
            <span>用户名</span>
            <input value="${user.name}" name="name" type="text" placeholder="请输入用户名">
          </div>
          <div class="seaction">
            <span>密码</span>
            <input value="${user.password}"  name="password" type="text" placeholder="请输入密码">
          </div>
          <div class="seaction">
            <span>年龄</span>
            <input value="${user.age}"  name="age" type="text" placeholder="请输入年龄">
          </div>
          <div class="seaction">
            <span>邮箱</span>
            <input value="${user.email}"  name="email" type="text" placeholder="请输入邮箱">
          </div>
            <div class="seaction">
              <span>请选择爱好</span>
              <div>
                
                
            
      `
      hobbies.forEach(item =>{
        // 判断当前循环是否在用户爱好中
        let isHobby = user.hobbies.includes(item);
        if(isHobby) {
          modify += `
          <label>
            <input type="checkbox" value="${item}" name="hobbies" checked>${item}
          </label>
          `
        }else{
          modify += `
          <label>
            <input type="checkbox" value="${item}" name="hobbies">${item}
          </label>
          `
        }
      })

      modify += `
            </div>
            <button type="submit">修改用户</button>
          </form>
        </div>
      </body>
      </html>
      `
      res.end(modify)
    } else if (pathname == '/remove') {
      await User.findOneAndDelete({_id: query.id})
      res.writeHead(301, {
        Location:'/list'
      });
      res.end();
    }

  } else if (method == 'POST') {
    if(pathname == '/add'){
      // console.log('yes i am post');
      // 1。接收用户信息，然后存储到数据库
      let formData = '';
      req.on('data',(param)=>{
        formData += param;
      })
      req.on('end',async ()=>{
        let user = querystring.parse(formData);
        await User.create(user);
        //301 重定向
        // location 跳转地址
        res.writeHead(301, {
          Location: '/list'
        })
        res.end();
      })

    } else if (pathname == '/modify') {
      // 接收用户提交信息
      let formData = '';
      // 接收psot参数
      req.on('data',(param)=>{
        formData += param;
      })
      // 参数接收完毕
      req.on('end',async ()=>{
        // 放到数据库
        let user = querystring.parse(formData);
        await User.updateOne({_id: query.id},user);
        //301 重定向
        // location 跳转地址
        res.writeHead(301, {
          Location: '/list'
        })
        res.end();
      })
    }
  }

})

app.listen(3000);